import jwt
from django.conf import settings
from django.http import JsonResponse

from users.models import UserProfile


def logging_check(func):
    def wrapper(self, request, *args, **kwargs):
        """
        装饰器逻辑代码
        1、获取token
        2、校验token
            失败:return{"code":403}
            成功:视图逻辑
        """
        # "b'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE2ODgwMTMyMTUsInVzZXJuYW1lIjoiemhhb2xpeWluZyJ9.j1yAzjnjOz5RQhePmcIcq3umqPe47xEkE7Hda9YC5SQ'"
        # get方法取出的是如上行所示的字符串，需要对其进行切片操作取出token
        token = request.META.get("HTTP_AUTHORIZATION")[2:-1]
        key = settings.JWT_TOKEN_KEY

        try:
            payload = jwt.decode(token, key, algorithms="HS256")
            # 若有问题则返回错误被下边捕捉
        except Exception as e:
            print(e)
            return JsonResponse({"code": 403})

        # 给所有用过装饰器的request增加一个对象
        username = payload.get("username")
        # 将username存入request
        user = UserProfile.objects.get(username=username)
        request.myuser = user

        return func(self, request, *args, **kwargs)
    return wrapper
